package action;

/**
 *添加到购物车
 */
import dao.CartItemDao;
import po.CartItem;
import po.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

@WebServlet(urlPatterns = "/user/action/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        Integer count = Integer.parseInt(req.getParameter("count"));
        String product = req.getParameter("product");
        //从session中获取user
        String phone = ((User) req.getSession().getAttribute("user")).getPhone();
        //创建购物车对象
        CartItem cartItem = new CartItem();
        //将获取的参数和user的phone绑定到购物车对象
        cartItem.setCount(count);
        cartItem.setProduct(product);
        cartItem.setUserId(phone);
        //判断购物车中是否存在该商品
        CartItemDao cartItemDao = new CartItemDao();
        CartItem cartItem1 = cartItemDao.selectByUserIdAndProduct(cartItem);
        Integer row = null;
        Writer writer = null;
        if (cartItem1 == null) {
            //如果购物车没有该商品则加入购物车
            row = cartItemDao.insert(cartItem);
        } else {
            //如果存在则将商品数目叠加
            cartItem1.setCount(cartItem1.getCount() + count);
            row = cartItemDao.update(cartItem1);
        }
        try {
            writer = resp.getWriter();
            if (row > 0) {
                writer.write("yes");
            } else {
                writer.write("no");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将购物车所有内容绑定到request
            //响应yes/no给浏览器

        }
    }
}